<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Webpatser\Uuid\Uuid;

class OrderController extends Controller
{
    public function create(Request $request)
    {
        $rule = [
            'uuid' => 'required|string',
            'type' => 'required',
            'total' => 'required',
        ];
        $message = [
            'uuid.required' => 'uuid不能为空',
            'type.required' => 'type字段不能为空',
            'total.required' => 'total字段不能为空',
        ];

        $valid = Validator::make($request->all(), $rule, $message);
        if ($valid->fails()) {
            $this->code = 1;
            $this->msg = $valid->errors()->first();
            return $this->json();
        }

//        try {
        $save_data['uuid'] = $request->uuid;
        $save_data['type'] = $request->type;
        $save_data['total'] = $request->total;
        if($request->type == 1){
            $note = '积分充值';
        }elseif($request->type == 2){
            $note = '会员充值-1个月';
        }elseif($request->type == 3){
            $note = '会员充值-永久';
        }
        $save_data['note'] = $note;
        $order_id = UUID::generate()->uuid_ordered;
        $save_data['order_id'] = $order_id;
        $id = Order::add($save_data);

//        }catch (\Exception $e){
//            $this->msg  = is_numeric($e->getCode())? $e->getMessage(): "操作失败";
//            $this->code = 1;
//        }
        $this->data['order_id'] = $order_id;
        return $this->json();
    }
    public function getList(Request $request)
    {
        $rule = [
            'uuid' => 'required|string',
        ];
        $message = [
            'uuid.required' => 'uuid不能为空',
        ];

        $valid = Validator::make($request->all(), $rule, $message);
        if ($valid->fails()) {
            $this->code = 1;
            $this->msg = $valid->errors()->first();
            return $this->json();
        }
        $model = new Order();
        $where[] = ['status','<',99];

        if(isset($request->status) && !empty($request->status)){

            if($request->status == 2){
                $where[] = ['status' ,0];
            }else{
                $where[] = ['status' ,$request->status];
            }

        }
        if (isset($request->uuid) && $request->uuid != ''){
            $where[] = ['uuid' ,$request->uuid];
        }

        $model->data['num'] = $request->num;
        $model->data['page'] = $request->page;
        $model->data['where'] = $where;
        $model->data['select'] = 'id,order_id,note,total,do_time,status,type';
        $this->data = $model->getList();
        return $this->json();
    }

}
